<template>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="用户名" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-icon><timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.username }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="角色" width="180">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>{{ scope.row.role }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.role }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog
    v-model="dialogVisible"
    title="Tips"
    width="500"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="auto"
      style="max-width: 600px"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" disabled />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="form.role" placeholder="please select your role">
          <el-option label="管理员" value="1" />
          <el-option label="普通用户" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="个人简介" prop="desc">
        <el-input v-model="form.desc" type="textarea" />
      </el-form-item>
      <el-form-item label="头像" prop="avater">
        <el-upload
          class="avatar-uploader"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleChange"
        >
          <img
            v-if="form.avater"
            :src="
              isAvaterChange
                ? form.avater
                : `http://localhost:3000/${form.avater}`
            "
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="onSubmit(formRef)"> 更新 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { Timer } from "@element-plus/icons-vue";
import axios from "axios";
import { computed, onMounted, reactive } from "vue";
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

onMounted(async () => {
  getUserList();
});

let tableData = reactive([]);
const getUserList = async () => {
  const { code, data } = await axios.get("/admin/user/list");
  if (code === 200) {
    tableData.splice(0, tableData.length);
    data.forEach((item, index) => {
      tableData.push({
        ...item,
        role: item.role === "1" ? "管理员" : "用户",
      });
    });
  }
};
const handleDelete = async (index, row) => {
  const res = await axios.delete("/admin/user/delete", {
    params: { id: row._id },
  });
  getUserList();
};

const handleClose = () => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      dialogVisible.value = false;
    })
    .catch(() => {
      // catch error
    });
};
const handleEdit = async (index, row) => {
  dialogVisible.value = true;
  isAvaterChange.value = false;
  const { code, data } = await axios.get("/admin/getInfo");
  if (code === 200) {
    Object.assign(form, data);
  }
};

const dialogVisible = ref(false);
const formRef = ref();
const rules = reactive({
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }],
  role: [{ required: true, trigger: "blur", message: "请选择角色" }],
  avater: [{ required: true, trigger: "blur", message: "请上传头像" }],
});
let form = reactive({
  username: "",
  password: "",
  desc: "",
  role: "",
  avater: "",
  file: null,
});
let isAvaterChange = ref(false);
const handleChange = (file) => {
  console.log(file);
  isAvaterChange.value = true;
  const url = URL.createObjectURL(file.raw);
  form.avater = url;
  form.file = file.raw || form.file;
};

const onSubmit = (formEl) => {
  if (!formEl) {
    return;
  }
  formEl.validate((valid) => {
    if (valid) {
      const params = new FormData();
      for (let i in form) {
        params.append(i, form[i]);
      }
      axios.put("/admin/user/edit", params, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    }
  });
};
</script>
<style scoped lang="scss">
::v-deep {
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
